<template>
  <div class="container">
    <a-card class="general-card">
      <!-- 搜索区域 -->
      <a-row>
        <a-col :flex="1">
          <a-form :model="searchForm" layout="inline">
            <a-form-item label="视图名称">
              <a-input v-model="searchForm.name" placeholder="请输入视图名称" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleSearch">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button @click="resetForm">重置</a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :flex="'86px'" style="text-align: right">
          <a-button type="primary" @click="handleAdd">新建</a-button>
        </a-col>
      </a-row>
      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :pagination="pagination"
        row-key="viewId"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        style="margin-top: 16px"
      >
        <template #viewDesc="{ record }">
          <span>{{ formatDesc(record.viewDesc) }}</span>
        </template>
        <template #viewType="{ record }">
          <span>{{ formatType(record.viewType) }}</span>
        </template>
        <template #actions="{ record }">
          <a-space>
            <a-button type="text" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm content="确定删除该视图吗？" @ok="() => handleDelete(record)">
              <a-button type="text" status="danger">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <!-- 新建视图抽屉（全屏弹框） -->
    <ViewDesignerCreate
      :key="currentRecord?.viewId || 'create'"
      v-if="addModalVisible"
      :visible="addModalVisible"
      :record="currentRecord"
      :mode="currentRecord ? 'edit' : 'create'"
      fullscreen
      :footer="false"
      :closable="true"
      unmount-on-close
      @update:visible="addModalVisible = $event"
      @cancel="addModalVisible = false"
      @success="fetchList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import ViewDesignerCreate from "./viewDesignerCreate.vue";
import { listView } from "@/api/views";
// 使用全屏抽屉弹框打开创建页
const router = useRouter();
const searchForm = reactive({ name: "" });
const addModalVisible = ref(false);
const currentRecord = ref<any>(null);
const columns = [
  { title: "视图ID", dataIndex: "viewId" },
  { title: "视图名称", dataIndex: "viewName" },
  { title: "视图描述", slotName: "viewDesc" },
  { title: "视图类型", slotName: "viewType" },
  { title: "操作", slotName: "actions" },
];
const tableData = ref<any[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 5,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [5, 10, 20],
});
async function fetchList() {
  const payload: any = {
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    viewName: searchForm.name || undefined,
  };
  try {
    const res: any = await listView(payload as any);
    // 兼容不同返回结构：优先 data.list/records
    const data = res?.data || res;
    const list = data?.list || data?.records || data?.rows || [];
    const total = data?.total ?? list.length ?? 0;
    tableData.value = list;
    pagination.total = total;
  } catch (e) {
    console.error("加载视图列表失败", e);
  }
}
function handleSearch() {
  pagination.current = 1;
  fetchList();
}
function resetForm() {
  searchForm.name = "";
  pagination.current = 1;
  fetchList();
}
function onPageChange(page) {
  pagination.current = page;
  fetchList();
}
function onPageSizeChange(size) {
  pagination.pageSize = size;
  pagination.current = 1;
  fetchList();
}
function handleAdd() {
  console.log("点击新建");
  // 打开全屏弹框
  currentRecord.value = null;
  addModalVisible.value = true;
}
function handleEdit(record: any) {
  currentRecord.value = record;
  addModalVisible.value = true;
}
function handleDelete(record: any) {
  // TODO: 接口删除，删除成功后刷新
  console.warn("删除待对接接口", record);
}
function goBack() {
  router.push("/");
}

onMounted(() => {
  fetchList();
});

function formatDesc(desc?: string) {
  if (!desc) return '';
  return desc.length > 10 ? `${desc.slice(0, 10)}...` : desc;
}

function formatType(t?: string) {
  if (t === 'view') return '视图';
  if (t === 'process') return '流程视图';
  return t || '';
}
</script>

<style scoped>
.container {
  width: 100vw;
  height: 100vh;
  min-height: 0;
  min-width: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  background: #f2f3f5;
  padding: 20px;
  box-sizing: border-box;
}

.back-button {
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 1001;
  margin-bottom: 16px;
}

.general-card {
  margin-top: 60px;
}
</style>
